helper='
look README.md
'

rootpath=$(dirname $0)
binpath=$rootpath/FlameGraph
if [ ! -d $binpath ]; then
    tar -zxf $rootpath/FlameGraph.tar.gz -C $rootpath
fi

target=""
catch_time=30
output_path=$rootpath

while [ $# -gt 0 ]; do
    case "$1" in
        -p) target="-p $2" ;;
        -t) target="-t $2" ;;
        -T) catch_time=$2  ;;
        -o) output_path=$2 ;;
        *)  echo $helper && exit 1 ;;
    esac
    shift 2
done

if [ "$target" = "" ]; then
    if [ `ps -ef | grep gaussdb | wc -l` -gt 2 ]; then
        echo "too many gaussdb process, please specify one."
        exit 0
    fi
    procid=`ps -ef | grep gaussdb | grep -v grep | awk '{print $2}'`
    target="-p $procid"
fi


pid=`date '+%Y-%m-%d-%H-%M'`
stackfile=$rootpath/cool_${pid}.stacks
svgfile=$output_path/perf_cool_${pid}.svg

# TODO check yum install bcc
/usr/share/bcc/tools/offwaketime -f $catch_time $target > $stackfile
$binpath/flamegraph.pl --color=chain --title="Off-Wake Time Flame Graph" --countname=us < $stackfile > $svgfile

rm $stackfile -fr

echo $svgfile

